package com.jiandaoshou;

import android.os.Handler;
import android.os.Message;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.OrientationHelper;
import android.support.v7.widget.RecyclerView;
import android.widget.TextView;

import com.andview.refreshview.XRefreshView;
import com.andview.refreshview.XRefreshViewFooter;
import com.jiandaoshou.adapter.CaiWuAdapter;
import com.jiandaoshou.base.BaseActivity;
import com.jiandaoshou.entry.OrderMonthCount;
import com.jiandaoshou.entry.ShopBalanceEntry;
import com.jiandaoshou.http.APIDefine;
import com.jiandaoshou.http.Http;
import com.jiandaoshou.utils.DividerItemDecoration;
import com.jiandaoshou.utils.JsonUtil;
import com.jiandaoshou.utils.LogUtil;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;

public class CaiWuGuanliAct extends BaseActivity {
    private RecyclerView mRecyclerView;
    private XRefreshView xRefreshView;
    private LinearLayoutManager LayoutManager;
    private CaiWuAdapter adapter;
    private List<OrderMonthCount> datas;
    private String shopID;
    private int year;
    //设置为true标示上拉刷新
    private boolean flag = true;
    private TextView Tv_Total_Acount;
    private TextView Tv_TiXian;
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 0:
                    //上拉刷新
                    if (flag) {
                        xRefreshView.stopRefresh();
                    } else {
                        xRefreshView.stopLoadMore();
                    }
                    if (datas.size() == 0) {
                        xRefreshView.setLoadComplete(true);
                    }
                    adapter.notifyDataSetChanged();
                    break;
                case 1:
                    ShopBalanceEntry entry= (ShopBalanceEntry) msg.obj;
                    LogUtil.e(entry.getShopBalance()+"  ");
                    String total=entry.getShopBalance();
                    if(total.equals("")){
                     total="0.0";
                    }
                    String acount=entry.getNoOperationApply();
                    if(acount.equals("")){
                      acount="0.0";
                    }
                    Float num=Float.valueOf(total)-Float.valueOf(acount);
                    Tv_TiXian.setText("￥ "+num+"");
                    Tv_Total_Acount.setText("￥ "+entry.getShopBalance());
                    break;
            }

        }
    };

    @Override
    public boolean showBackLogo() {
        return true;
    }

    @Override
    protected int getContentViewRes() {
        return R.layout.activity_caiwuguanli;
    }

    @Override
    protected String getTitleText() {
        return "财务管理";
    }

    @Override
    public void init() {
        datas = new ArrayList<OrderMonthCount>();
        Calendar cal = Calendar.getInstance();
        year = cal.get(Calendar.YEAR);//获取年份
        mRecyclerView = $(R.id.recycler_caiwuguanli);
        xRefreshView = $(R.id.custom_view);
        Tv_Total_Acount=$(R.id.tv_total_account);
        Tv_TiXian=$(R.id.tv_ketixian);
        //设置布局管理器
        LayoutManager = new LinearLayoutManager(this);
        LayoutManager.setOrientation(OrientationHelper.VERTICAL);
        mRecyclerView.setLayoutManager(LayoutManager);
        mRecyclerView.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL_LIST));
        //设置增加或删除条目的动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        mRecyclerView.setHasFixedSize(true);
        adapter = new CaiWuAdapter(CaiWuGuanliAct.this, datas);
        xRefreshView.setHideFooterWhenComplete(false);
        adapter.setCustomLoadMoreView(new XRefreshViewFooter(CaiWuGuanliAct.this));
        mRecyclerView.setAdapter(adapter);
        shopID = getIntent().getStringExtra("shopId");
        GetAcountData();
        GetData(year,0);
        xRefreshView.setXRefreshViewListener(new XRefreshView.SimpleXRefreshListener() {
            @Override
            public void onRefresh() {
                super.onRefresh();
                flag = true;
                datas.clear();
                year = Calendar.getInstance().get(Calendar.YEAR);//获取年份
                GetData(year,1);
            }

            @Override
            public void onLoadMore(boolean isSilence) {
                super.onLoadMore(isSilence);
                flag = false;
                year--;
                GetData(year,2);
            }
        });
    }

    private void GetAcountData(){
        HashMap<String, String> map = new HashMap<>();
        map.put("strShopID", shopID);
        Http.post(APIDefine.TF_Interface_GetShopBalance, map, new Http.HttpCallBack() {
            @Override
            public void onHttpSuccess(String response) throws Exception {
                ShopBalanceEntry entry = JsonUtil.parser.fromJson(response, ShopBalanceEntry.class);
                String total=entry.getShopBalance();
                if(total.equals("")){
                    total="0.0";
                }
                String acount=entry.getNoOperationApply();
                if(acount.equals("")){
                    acount="0.0";
                }
                Float num=Float.valueOf(total)-Float.valueOf(acount);
                Tv_TiXian.setText("￥ "+num+"");
                Tv_Total_Acount.setText("￥ "+total);
            }
        });
    }

    private void GetData(int year, final int type) {
        shopID = getIntent().getStringExtra("shopId");
        //获取按照月份获取订单量
        HashMap<String, String> map = new HashMap<>();
        map.put("strShopID", shopID);
        map.put("strYear", year + "");
        Http.post(APIDefine.TF_Interface_GetMonthToTal, map, new Http.HttpCallBack() {
            @Override
            public void onHttpSuccess(String response) throws Exception {
                JSONObject object = new JSONObject(response);
                JSONArray array = object.getJSONArray("List");
                OrderMonthCount order;
                if(array.length()==0){
                    return;
                }
                for (int i = 0; i < array.length(); i++) {
                    order = JsonUtil.parser.fromJson(array.get(i).toString(), OrderMonthCount.class);
                    datas.add(order);
                }
                sortClass info=new sortClass();
                Collections.sort(datas,info);
                adapter.notifyDataSetChanged();
                if (array.length() < 10) {
                    xRefreshView.setLoadComplete(true);
                    xRefreshView.stopLoadMore();
                }
                //上拉刷新
                if(type==1){
                    xRefreshView.stopRefresh();
                }else{
                    xRefreshView.stopLoadMore();
                }
            }
        });
    }
    //按照日期排序
    public class sortClass implements Comparator{
        public int compare(Object arg0,Object arg1){
            OrderMonthCount user0 = (OrderMonthCount)arg0;
            OrderMonthCount user1 = (OrderMonthCount)arg1;
            int flag = user0.getMonth().compareTo(user1.getMonth());
            return flag;
        }
    }
}
